package com.example.conversorcplp;

import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.conversorcplp.Rates;

public class ActualizaTaxas extends Activity {
	
	private static final String API_URL = "http://openexchangerates.org/api/latest.json?app_id=8348229b2e8e4ebfa4f74ced602b2a87";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.taxas);
		
		Button btn = (Button) findViewById(R.id.button1);
		
		btn.setOnClickListener(new OnClickListener(){
			
		    public void onClick(View v){      
		    	
		    	AsyncHttpClient client = new AsyncHttpClient();
				client.get(API_URL, new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(Throwable arg0, String arg1){
						super.onFailure(arg0,arg1);
					}
					
					@Override
					public void onFinish() {
						super.onFinish();
					}
					
					@Override
					public void onStart() {
						super.onStart();
					}
					
					@Override
					public void onSuccess(String response){
						Log.i("CPLP", "HTTP Sucess");
						try {
							JSONObject jsonObj = new JSONObject(response);
							JSONObject ratesObject = jsonObj.getJSONObject("rates");
							
							Rates.kwanzaRate = ratesObject.getDouble("AOA");
							Rates.brazilRate = ratesObject.getDouble("BRL");
							Rates.cverdeRate = ratesObject.getDouble("CVE");
							Rates.equaRate = ratesObject.getDouble("XAF");
							Rates.guineRate = ratesObject.getDouble("GNF");
							Rates.mocambiRate = ratesObject.getDouble("MZN");
							Rates.eurRate = ratesObject.getDouble("EUR");
							Rates.stpRate = ratesObject.getDouble("STD");
							Rates.timorRate = ratesObject.getDouble("USD");
							Rates.usdRate = ratesObject.getDouble("USD");
							
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
				});
				Toast.makeText(getApplicationContext(), "Taxas actualizadas!", Toast.LENGTH_SHORT).show();
		    }
		});
		
	}
}